<?php

namespace yphp;

/**
 * Class config
 * 配置读取类
 */
class Config extends Instance
{
    # 配置项
    private static $config;
    # 配置数组
    private static $read = [];

    // 初始化
    static function init()
    {
        if (is_null(self::$config)) {
            $config_dir = dir(YP . 'config' . DS);
            while (($path = $config_dir->read()) !== false) {
                if ($path === '.' || $path === '..') continue;
                self::$config[] = substr($path, 0, -4);
            }
        }
        return self::$config;
    }

    // 加载配置
    static function __callStatic($name, $arguments)
    {
        $isSpot = substr($name,-4) === 'Spot';
        $name = $isSpot ? substr($name, 0, -4) : $name;
        $list = self::init();
        if(!in_array($name, $list)) throw new \Exception('配置方法' . $name . '不存在');
        return count($arguments) > 0 ? self::get($isSpot ? $arguments : explode('.', join('.', $arguments)), self::find($name), $name) : self::find($name);
    }

    // 注册配置
    static function reg($name)
    {
        $list = self::init();
        if(in_array($name, $list)) throw new \Exception('配置项' . $name . '已配置');
        self::$config[] = $name;
    }

    // 读取配置
    private static function get($getArr, $cofArr, $name)
    {
        if (key_exists($key = array_shift($getArr), $cofArr)){
            return empty($getArr) ? $cofArr[$key] : self::get($getArr, $cofArr[$key], $name);
        }

        throw new \Exception($name . '里的配置' . $key . '不存在');
    }

    // 解析配置项
    private static function find($confname)
    {
        if (!key_exists($confname, self::$read)) {
            $app = self::getApp($confname);
            # 如果应用配置有database,nosql配置则合并一个空数组，否则读取框架配置
            $web = ($app && in_array($confname, ['database','nosql'])) ? [] : self::getWeb($confname);
            self::$read[$confname] = self::merge($web, $app);
        }
        return self::$read[$confname];
    }

    // 获取框架配置
    private static function getWeb($name)
    {
        return Yphp::loadfile(YP . 'config' . DS . $name . '.php') ?: [];
    }

    // 获取应用配置
    private static function getApp($name)
    {
        return Yphp::loadfile(CONFIG . $name . '.php') ?: [];
    }

    // 合并配置项
    private static function merge($web, $app)
    {
        foreach ($web as $k => $w) {
            if (!key_exists($k, $app)) {
                $app[$k] = $w;
            } elseif ($w !== $app[$k] && is_array($w)) {
                $app[$k] = self::merge($w, $app[$k]);
            }
        }
        return $app;
    }

}